<!-- 添加商品列表 -->
<template>
   <div>
  <el-card class="box-card">
   <p class="text">商品(Spu)介绍</p>
   <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <!-- 商品名称 -->
    <el-form-item label="商品名称" prop="title">
      <el-input v-model="ruleForm.title" autocomplete="off" />
    </el-form-item>
    <!-- 原始价格 -->
    <el-form-item label="原始价格" prop="originalPrice">
      <el-input  placeholder="请输入" v-model="ruleForm.originalPrice"><template #append>元</template></el-input>
    </el-form-item>
    <!-- 当前价格 -->
    <el-form-item label="当前价格" prop="price">
      <el-input  placeholder="请输入"  v-model="ruleForm.price"><template #append>元</template></el-input>
    </el-form-item>
    <!-- VIP价格 -->
    <el-form-item label="VIP价格" prop="vipPrice">
      <el-input  placeholder="请输入"  v-model="ruleForm.vipPrice"><template #append>元</template></el-input>
    </el-form-item>
    <!-- 剩余库存 -->
    <el-form-item label="剩余库存">
      <el-input v-model="ruleForm.stock" autocomplete="off" disabled/>
    </el-form-item>
    <!-- 运费模板 -->
    <el-form-item label="运费模板">
      <el-select placeholder="选择商品运费模板" style="width: 200px;margin-right: 10px;" v-model="ruleForm.freightTemplateId">
            <el-option :label="item.title" :value="item.id" v-for="item in freightlist" />
         </el-select>
    </el-form-item>
    <!-- 是否在售 -->
    <el-form-item label="是否在售" prop="status">
      <el-radio-group  class="ml-4" v-model="ruleForm.status">
      <el-radio :label="1">在售</el-radio>
      <el-radio :label="0">下架</el-radio>
    </el-radio-group>
    </el-form-item>
    <!-- 商品图片 -->
    <el-form-item label="商品图片">
  <el-upload
    :file-list="ruleForm.imgList"
    action="http://192.168.1.188:8080/upload/admin" :headers="headers" :limit="5"
    list-type="picture-card" :on-exceed="number"
    :on-success="handleAvatarSuccess"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
    </el-form-item>
    <!-- 商品单位 -->
    <el-form-item label="商品单位" prop="unit">
      <el-input v-model="ruleForm.unit" autocomplete="off" placeholder="件/个/盒"/>
    </el-form-item>
   <el-form-item label="所属类目">
      <el-cascader :options="options" placeholder="请选择" :props="{ children: 'childrenList', 
      label: 'title', value: 'id', emitPath: false }" v-model="ruleForm.categoryId"/>
   </el-form-item>
   <!-- 商品简介 -->
   <el-form-item label="商品简介" >
      <el-input v-model="ruleForm.description" autocomplete="off"/>
    </el-form-item>
    <!-- 富文本 -->
    <el-form-item label="商品详细介绍" prop="detail">
      <TEditor style="width: 100%;" v-model="ruleForm.detail"/>
    </el-form-item>
  </el-form>
  </el-card>
  <!-- 商品参数 -->
  <el-card class="box-card">
    <p class="text">商品参数</p>
    <el-row class="mb-4">
    <el-button type="primary" plain @click="handleopen">添加</el-button>
    <el-table :data="ruleForm.attributeList" style="width: 100%">
    <el-table-column prop="attribute" label="商品参数名称"  />
    <el-table-column prop="value" label="商品参数值"  />
    <el-table-column prop="" label="操作" >
      <template #default="scope">
      <el-button type="danger" @click="deletevalue(scope.$index)">删除</el-button>
    </template>
    </el-table-column>
  </el-table>
  </el-row>
  <!-- 商品参数弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="设置商品参数" width="30%" destroy-on-close>
    <el-form :model="tableDatas" ref="ruleFormRefs" :rules="rules">
      <el-form-item label="商品参数名称" :label-width="formLabelWidth" prop="attribute">
        <el-input v-model="tableDatas.attribute" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品参数值" :label-width="formLabelWidth" prop="value">
        <el-input v-model="tableDatas.value" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="shopvalue(ruleFormRefs)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</el-card>
<!-- 规格维度 -->
<el-card class="box-card">
  <p class="text">规格维度</p>
    <el-row class="mb-4">
    <el-table :data="ruleForm.specificationList" style="width: 100%">
    <el-table-column prop="id" label="维度ID"  />
    <el-table-column prop="title" label="维度名称"  />
    <el-table-column prop="gmtCreate" label="创建时间" >
      <template #default="scope">
        <p>{{ friendTime(scope.row.gmtCreate) }}</p>
      </template>
    </el-table-column>
  </el-table>
  </el-row>
</el-card>
<!-- 商品(Sku)详情 -->
<el-card class="box-card">
  <p class="text">商品(Sku)详情</p>
    <el-button type="primary" plain @click="BatchPricing=true" :disabled="ruleForm.skuList.length==0">批量定价</el-button>
    <!-- 批量定价弹窗 -->
   <el-dialog v-model="BatchPricing" title="批量定价" width="30%" destroy-on-close>
    <el-form :model="batch" ref="ruleFormRef" :rules="rules">
      <el-form-item label="现价(￥)" :label-width="formLabelWidth" >
        <el-input-number :min="1" size="small" v-model="batch.price"></el-input-number>
      </el-form-item>
      <el-form-item label="VIP价格(￥)" :label-width="formLabelWidth" >-
        <el-input-number :min="1" size="small" v-model="batch.vipPrice"></el-input-number>
      </el-form-item>
      <el-form-item label="吊牌价(￥)" :label-width="formLabelWidth" >
        <el-input-number :min="1" size="small" v-model="batch.originalPrice"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="BatchPricing = false">取消</el-button>
        <el-button type="primary" @click="Batchprice">确定</el-button>
      </span>
    </template>
  </el-dialog>
       <el-row style="margin: 10px;" v-for="(item,index) in ruleForm.specificationList" :key="index">
      <el-tag type="warning" style="margin-right: 10px;">{{ item.title}}</el-tag>

      <el-tag closable v-for="(ite,indexs) in item.values" :key="indexs" @close="handleClose(item,indexs)">{{ ite }}</el-tag>

      <el-input v-model.trim="inputValue" autocomplete="off" size="small" @blur="addinputchange(item)"
      style="width: 20%;" v-if="ruleForm.specificationList[index].bool" @keyup.enter="addinputchange(item)"/>

      <el-button size="small" :icon="Plus" @click="addinput(index)" v-else>添加</el-button>
  </el-row>
    <el-table :data="ruleForm.skuList" style="width: 100%" border :span-method="objectSpanMethod">
    <el-table-column v-for="(item, index) in ruleForm.specificationList" :prop="'sku_' + item.title" :label="item.title" width="80"/>
    <el-table-column prop="id" label="skuid"  width="80"/>
    <el-table-column prop="price" label="￥价格(元)" >
      <template #default="scope"><el-input-number :min="1" size="small" v-model="scope.row.price"/></template>
    </el-table-column>
    <el-table-column prop="vipPrice" label="￥VIP价(元)" >
      <template #default="scope"><el-input-number :min="1" size="small" v-model="scope.row.vipPrice"/></template>
    </el-table-column>
    <el-table-column prop="originalPrice" label="￥吊牌价(元)" >
      <template #default="scope"><el-input-number :min="1" size="small" v-model="scope.row.originalPrice" /></template>
    </el-table-column>
    <el-table-column prop="stock" :label="'库存('+(ruleForm.unit?ruleForm.unit:'件')+')'" >
      <template #default="scope"><el-input-number :min="1" size="small" v-model="scope.row.stock" /></template>
    </el-table-column>
    <el-table-column prop="weight" label="重量(克)" >
      <template #default="scope"><el-input-number :min="1" size="small" v-model="scope.row.weight" /></template>
    </el-table-column>
    <el-table-column prop="img" label="sku图片" width="80">
      <template #default="scope"><el-upload action="http://192.168.1.188:8080/upload/admin" :show-file-list="false" :headers="headers"
    :on-success="handleAvatarSuccesss"   :before-upload="beforeAvatarUpload"> <img v-if="scope.row.img" :src="scope.row.img" class="avatars" />
    <el-icon v-else @click="imgindex=scope.$index"><Upload /></el-icon>
  </el-upload>
</template>
    </el-table-column>
    <el-table-column prop="barCode" label="总条形码"  width="220">
      <template #default="scope">
        <el-input v-model="scope.row.barCode" ><template #append ><span @click="scope.row.barCode=new Date().getTime()">随机</span></template></el-input></template>
    </el-table-column>
  </el-table>
 
      
  </el-card>
  <p style="text-align: right;"><el-button @click="closeForm">关闭</el-button> <el-button type="primary" @click="submitForm(ruleFormRef)">修改商品</el-button></p>
   </div>
</template>
<script lang="ts" setup>
import { reactive, ref ,onMounted,watch} from 'vue'
import type { FormInstance } from 'element-plus'
import {get,post} from '@/utlis/http'
import {Classgoodscreate} from '#/index'
import { ElMessage,ElMessageBox } from 'element-plus'
import Cookies from 'js-cookie'
import { Plus,Upload } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import TEditor from '@/components/TEditor.vue'
import {friendTime} from '@/utlis/PackagingTime'
import {useRouter,useRoute} from 'vue-router'
import {useTagsStore,} from '@/stores/tag'
let router=useRouter()
let route=useRoute()
const store=useTagsStore()
const options=ref()//所属类目
const freightlist=ref()//加载模板
const ruleFormRef = ref<FormInstance>()//节点
const ruleForm = reactive(new Classgoodscreate())//当前页面所有数据的一个对象
// 价格逻辑判断
const verificationprice=(rule: any, value: any, callback: any)=>{
        if (value==='') {
          callback(new Error('价格不能为空'))
        } else if(Number(ruleForm.price) >Number(ruleForm.originalPrice) ||Number(ruleForm.vipPrice) >Number(ruleForm.price)){
          callback(new Error('原价格不能低于优惠，当前价不能低于vip价'))
        }
        callback()//回调
}
// 单位只能输入个，件、盒
const verificationunit=(rule: any, value: any, callback: any)=>{
        if (!value) {
          callback(new Error('单位不能为空'))
        } else if(ruleForm.unit!='件' && ruleForm.unit!='个' && ruleForm.unit!='盒'){
          callback(new Error('请输入正确的单位！'))
        }
        callback()
}
// 非空验证
const rules = reactive({
  title: [{message: '名称不能为空！', trigger: 'blur' ,required: true}],
  detail: [{message: '详情介绍不能为空！', trigger: 'blur' ,required: true}],
  price: [{message: '当前价格不能为空', trigger: 'blur' ,required: true},
  {pattern:/^(\d+.?)?\d{0,2}$/,message:'请输入数字并且小数只能两位'}],
  vipPrice:[{ validator: verificationprice }, 
  { required: true, pattern: /^(\d+.?)?\d{0,2}$/, message: '请输入数字或者2位的小数' }],
  status: [{message: '状态不能为空！', trigger: 'blur' ,required: true}],
  unit: [{validator: verificationunit, trigger: 'blur' ,required: true}],
  attribute: [{message: '商品参数名称不能为空！', trigger: 'blur' ,required: true}],
  value: [{message: '商品参数值不能为空！', trigger: 'blur' ,required: true}],
  originalPrice: [{message: "原价不能为空", trigger: 'blur' ,required: true},
  {pattern:/^(\d+.?)?\d{0,2}$/,message:'请输入数字并且小数只能两位'}],

})
// 获得详情列表
let prop=defineProps(['id'])//传过来的id后台请求
function init(){
  console.log(555,prop.id);
  
   get({_gp:'admin.product',_mt:'detail',spuId:prop.id}).then(res=>{
      let {errno,data,errmsg}=res
      if (200==errno) {
        console.log(data);
        //  uploadImgList.value.push(...data.imgList.map((item:string,index:number)=>{//处理图片数组换成标签初始格式
        //     return{
        //        name:index+"",//name:index+''下标转字符串
        //        url:item
        //     }   
        data.imgList = data.imgList.map((item: string) => {
        return item.startsWith('{') ? JSON.parse(item).url.startsWith('{') ? { url: JSON.parse(JSON.parse(item).url).url } : { url: JSON.parse(item).url } : { url: item }   //判断是否是对象，如果以{开头代表对象
      }) 
         
         data.specificationList=data.skuList[0].specification.split(',')
          /*
          先将字符串通过split分割字符串数组['尺码_S', '颜色_经典款短袖黑色A尺码_S', '颜色_经典款短袖黑色A', '尺码_S']
         */
          .map((item:string)=>item.split('_')[0])
          /*
          再通过split通过_继续分割，太多相似的只取下标第一个['尺码', '颜色', '颜色', '尺码', '颜色', '尺码']
          */
          .map((items:string)=>data.specificationList.find((v:any)=>v.title===items))
        // //  最后进行查找处理后的与原本标题的是否全等于然后返回所有元素
         data.specificationList = data.specificationList.map((item:any)=>({//内部添加属性values定义空数组
            ...item,
            values:[]
        }))
         data.skuList.forEach((item:any)=>{
           let spec= item.specification||''//拿到所有规格的字符串
           /*通过split分割字符串数组['尺码_S', '颜色_经典款短袖黑色A尺码_S', '颜色_经典款短袖黑色A', '尺码_S']*/
           spec.split(',').map((item:string)=>item.split('_')).forEach((ite:string)=>{/*['尺码', 'S']['颜色','经典款短袖黑色A']*/
            let title=ite[0]//尺码,颜色
            let val=ite[1]//s,经典款短袖黑色A
            item["sku_"+title]=val//sku_尺码: "s",sku_颜色: "经典款短袖黑色A"
            var findspec=data.specificationList.find((item:any)=>item.title===title)
            var index=findspec?.values.indexOf(val)
            if (index===-1) {
               findspec.values.push(val)
            }
           })
         })
         Object.assign(ruleForm,data)
      }else{
         ElMessage.error(errmsg)
      }
    })
  
}
// 加载模板与类目
function loadfreingt(){
  console.log(999);
    get({_gp:'admin.freight',_mt:'list'}).then(res=>{
      freightlist.value=res.data
    })
    let data={
    _gp:'admin.category',
  _mt:'categoryTree'
  }
  get(data).then(res=>{
    options.value=res.data
    
  })
}
//监听缓存
// watch(route,(route)=>{
// uploadImgList.value=[]
//     init()//模板
// })
// 挂载
onMounted(() => {
  
  loadfreingt()//模板
  init()//渲染
})

// 将图片添加到ruleForm.imgList数组
const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  ruleForm.imgList.push(response.url)//多张图片提取出路径
  ruleForm.img=ruleForm.imgList[0]//只要第一张图片
}
// sku图片
let imgindex=ref()
const handleAvatarSuccesss: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.skuList[imgindex.value].img = response.url//根据下标添加图片
}
let headers = reactive({//获得请求头
   'AdminToken': Cookies.get('token')
})
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只允许image/jpeg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过2MB!!')
    return false
  }
  return true
}
// 图片超出限制提示
function number(){
  ElMessage.warning('最多5张图不能再多了')
}
// 商品参数列表绑定数据
let tableDatas =ref({
  attribute:'',
  value:''
})
let dialogFormVisible=ref(false)//商品参数控制显示隐藏
const formLabelWidth='100px'
// 商品参数弹出框
function handleopen(){//商品参数弹出时数据清空
  dialogFormVisible.value = true
  tableDatas.value={
    attribute:'',
    value:''
  }
}
// 商品参数确认
const ruleFormRefs = ref<FormInstance>()
function shopvalue(formEl: FormInstance | undefined){
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 空数组添加内容
  ruleForm.attributeList.push({...tableDatas.value})//添加给最大的对象
  dialogFormVisible.value = false
    } else {
      console.log('error submit!')
      return false
    }
  })
  
}
// 商品参数删除
function deletevalue(index:number){
console.log(index);
ruleForm.attributeList.splice(index,1)//删除当前规格一行
}
let inputValue=ref()//批量定价的双向绑定
// 点击添加显示输入框通过添加属性实现
function addinput(index:number){
  ruleForm.specificationList[index].bool=true
}
// 输入框键盘按下事件，将输入的内容添加给当前行
function addinputchange(item:any){
  let inde=item.values.findIndex((i:string)=>i==inputValue.value)
  if (inputValue.value) {
    // 去重操作
    if (inde==-1) {
      item.values.push(inputValue.value)
      createtabie()
    } else {
      ElMessage.error('名称已存在了哟！')
    } 
  }
  item.bool=false
  inputValue.value=''//添加完为空
  
}
// 关闭tag标签
const handleClose = (item:any,index:number) => {
  item.values.splice(index,1)
  createtabie()
}
// 笛卡尔交叉算法算法
function createtabie(){
  let valuelist=ruleForm.specificationList.filter(item=>item.values.length).map(item=>item.values)//拿到标题数组
  let titles=ruleForm.specificationList.map(item=>item.title)//拿到标题 ['尺码', '颜色']
  if (valuelist.length==0) {//没有标题的长度将sku赋值为空
    ruleForm.skuList = [];//其他地方删除将当前清空
    return
  }
   var skulist=valuelist.reduce((per:string[][],next:[])=>{//数组标题与属性值
    
    var array:string[][]=[]//定位空数组
    per.forEach(i => {
      next.forEach(s=>{
        array.push(i.concat([s]))//
      })
    });
    return array
  },[[]])
  let {price,vipPrice,originalPrice}=ruleForm//先拿到前面输入的price当前价格，vipPrice，originalPrice原价
 let skuLists=skulist.map((item:string[][])=>{ //['S', '薄款连帽橙色A']['S', '薄款连帽黑色A']['L', '薄款连帽橙色A']['L', '薄款连帽黑色A']
    let obj:any={
      price,
      vipPrice,
      originalPrice,
      stock:'',
      weight:undefined,
      img:'',
      barCode:'',
      titleArray:new Array<string>(),
      specificationArray:new Array<string>(),
      title:'',
      specification:''
    }
    item.forEach((val,index)=>{
      obj['sku_' + titles[index]] = val;//sku_尺码: "S",sku_颜色: "薄款连帽橙色A"
      obj.titleArray.push(val)//['S', '薄款连帽橙色A']
      obj.specificationArray.push(titles[index]+"_"+val)//['尺码_S', '颜色_薄款连帽橙色A']
      obj.title=obj.titleArray.join(",")//"S,薄款连帽橙色A"
    obj.specification=obj.specificationArray.join(",")//['尺码_S', '颜色_薄款连帽橙色A']
    })
    return obj
  })
  Object.assign(ruleForm.skuList,skuLists)
}

// 批量定价弹窗
let batch=ref({
  price:0,
  vipPrice:0,
  originalPrice:0
})
let BatchPricing=ref(false)
// 批量定价赋值价格
function Batchprice(){
  for (const o of ruleForm.skuList) {
        o.price=batch.value.price
        o.vipPrice=batch.value.vipPrice
        o.originalPrice=batch.value.originalPrice
  }
  BatchPricing.value=false
  
}
// 合并表格
function objectSpanMethod ({rowIndex, columnIndex}:{rowIndex:number,columnIndex:number}){
  let speclist=ruleForm.specificationList.filter(item=>item.values.length>0)//获取规格列表
  if (columnIndex<speclist.length-1) {//行小于规格列表-1就是最后一个时赋值为1
    let num=1
    for (let index = columnIndex+1; index < speclist.length; index++) {//循环所有行下标小于规格列表
      num *=speclist[index].values.length
    }
    if (rowIndex%num===0) {
      return {rowspan:num,colspan: 1}
    } else {
      return {rowspan:0,colspan: 0}
    }
    
  }

}



  // 表单验证
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
     let updateshop={
      _gp:'admin.product',
      _mt:'edit',
      spuDTO:JSON.stringify({...ruleForm})
     }
     post(updateshop).then(res=>{
      if (200===res.errno) {
        ElMessageBox.confirm('编辑成功是否继续添加?',
    '提示',
    {
      confirmButtonText: '继续',
      cancelButtonText: '取消',
      type: 'success',
    }
  )
    .then(() => {
      window.history.go(0)
    })
    .catch(() => {
      router.push({path:'/index/goodstube/Goodslist'})
    })
      } else {
        ElMessage.error(res.errmsg)
      }
     })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 添加编辑关闭按钮
function closeForm(){
  store.removebuttom(route.path)
  router.push({path:'/index/goodstube/Goodslist'})
}

</script>
<style scoped lang="less">
.box-card {
  width: 100%;
  .text{
   font-weight: bold;
  }
  .avatar-uploader .avatar {
   width: 178px;
   height: 178px;
   display: block;
}
.avatars{
  width: 50px;
   height: 50px;
}
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>